package com.java1234.jxc.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.java1234.jxc.beans.SysLog;
import com.java1234.jxc.beans.SysMenu;
import com.java1234.jxc.beans.SysRole;
import com.java1234.jxc.beans.SysUser;
import com.java1234.jxc.service.LogService;
import com.java1234.jxc.service.MenuService;
import com.java1234.jxc.service.RoleService;
import com.java1234.jxc.service.UserService;
import com.java1234.jxc.utils.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/3/17.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @Autowired
    private LogService logService;


    @ResponseBody
    @RequestMapping("/login")
    public Map<String,Object> login(String imageCode, String userName, String password, HttpSession session){
        Map<String,Object> result = new HashMap<>();
        if (StringUtil.isEmpty(imageCode)){
            result.put("success",false);
            result.put("errorInfo","请输入验证码!");
            return result;
        }

        if (!session.getAttribute("checkcode").equals(imageCode)){
            result.put("success",false);
            result.put("errorInfo","验证码输入错误!");
            return result;
        }

        if (StringUtil.isEmpty(userName)){
            result.put("success",false);
            result.put("errorInfo","用户名不能为空!");
            return  result;
        }
        if (StringUtil.isEmpty(password)){
            result.put("success",false);
            result.put("errorInfo","密码不能为空!");
            return  result;
        }


        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);

        try{
            subject.login(token);
            userName= (String) SecurityUtils.getSubject().getPrincipal();
            SysUser currentUser = userService.findByUserName(userName);
            List<SysRole> roleList = roleService.findByUserId(currentUser.getId());
            //result.put("currentUser",currentUser);
            session.setAttribute("currentUser",currentUser);
            result.put("roleList",roleList);
            result.put("roleSize",roleList.size());
            result.put("success",true);
            logService.insert(new SysLog(SysLog.LOGIN_ACTION,userName));
            return result;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            result.put("success",false);
            result.put("errorInfo","用户名或密码错误!");
            return result;

        }
    }


    /**
     * 保存角色信息
     * @param roleId
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveRole")
    public Map<String,Object> saveRole(Integer roleId,HttpSession session){
        Map<String,Object> result  = new HashMap<>();
        SysRole currentRole = roleService.findById(roleId);
        session.setAttribute("currentRole",currentRole);
        result.put("success",true);
        return result;
    }

    /**
     * 加载当前用户信息
     * @param session
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/loadUserInfo")
    public String loadUserInfo(HttpSession session)throws Exception{
        SysUser currentUser = (SysUser) session.getAttribute("currentUser");
        SysRole currentRole = (SysRole) session.getAttribute("currentRole");
        String result ="欢迎您"+currentUser.getTrueName()+"&nbsp;[&nbsp;"+currentRole.getName()+"&nbsp;]";
     //   System.out.println(result);
        return result;
    }

    @ResponseBody
    @PostMapping("/loadMenuInfo")
    public String loadMenuInfo(HttpSession session,Integer parentId)throws Exception{
        SysRole currentRole = (SysRole)session.getAttribute("currentRole");
        return getAllMenuByParentId(parentId,currentRole.getId()).toString();
    }


    /**
     * 获取所有菜单信息
     * @param parentId
     * @param roleId
     * @return
     */
    public JsonArray getAllMenuByParentId(Integer parentId,Integer roleId){
        JsonArray jsonArray = this.getMenuByParentId(parentId,roleId);
        for(int i=0;i<jsonArray.size();i++){
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            if ("open".equals(jsonObject.get("state").getAsString())){
                continue;
            }else{
                jsonObject.add("children",getAllMenuByParentId(jsonObject.get("id").getAsInt(),roleId));
            }

        }
        return jsonArray;
    }


    /**
     * 根据父节点和用户角色ID查询菜单
     * @param parentId
     * @param roleId
     * @return
     */
    public JsonArray getMenuByParentId(Integer parentId,Integer roleId){
        List<SysMenu> menuList = menuService.findByParentIdAndRoleId(parentId, roleId);
        JsonArray jsonArray = new JsonArray();
        for (SysMenu menu:menuList){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id",menu.getId());
            jsonObject.addProperty("text",menu.getName());

            if (menu.getState()==1){
                jsonObject.addProperty("state","closed"); // 根节点
            }else{
                jsonObject.addProperty("state","open"); // 叶子节点
            }
            jsonObject.addProperty("iconCls",menu.getIcon());   // 节点图标
            JsonObject attributeObject = new JsonObject();  //扩展属性
            attributeObject.addProperty("url",menu.getUrl()); // 菜单请求地址
            jsonObject.add("attributes",attributeObject);
            jsonArray.add(jsonObject);

        }

        return jsonArray;
    }



}
